#include "connection.h"

/*  Read a line from a socket  */

ssize_t Readline(int sockd, void *vptr, size_t maxlen)
{
    ssize_t n, rc;
    char    c, *buffer;

    buffer =(char*) vptr;

    for ( n = 1; (unsigned int)n < maxlen; n++ ) {
	
	if ( (rc = read(sockd, &c, 1)) == 1 ) {
	    *buffer++ = c;
	    if ( c == '\n' )
		break;
	}
	else if ( rc == 0 )
	{
	    if ( n == 1 )
		return 0;
	    else
		break;
	}
	else {
	    if ( false/* errno == EINTR*/ )
		continue;
	    return -1;
	}
    }

    *buffer = 0;
    return n;
}


/*  Write a line to a socket  */

ssize_t Writeline(int sockd, const void *vptr, size_t n) {
    size_t      nleft;
    ssize_t     nwritten;
    const char *buffer;

    buffer = (char*) vptr;
    nleft  = n;

    while ( nleft > 0 ) {
	if ( (nwritten = write(sockd, buffer, nleft)) <= 0 ) {
	    if ( false/*errno == EINTR */)
		nwritten = 0;
	    else
		return -1;
	}
	nleft  -= nwritten;
	buffer += nwritten;
    }

    return n;
}


Connection::Connection(int socket, RunMode mode) : Processor(mode)
{
	m_socket = socket;
}
	
void Connection::Process()
{
	//char      buffer[1000];      /*  character buffer          */
	
	/*  Retrieve an input line from the connected socket
	    then simply write it back to the same socket.     */
	//Readline(m_socket, buffer, 999);
	//Writeline(m_socket, buffer, strlen(buffer));
	
	FILE *fpipe;
   char command[256]= "sh test.sh";
   char line[256];

   if ( !(fpipe = (FILE*)popen(command,"r")) )
   {  // If fpipe is NULL
      //perror("Problems with pipe");
      exit(1);
   }

	while (!feof(fpipe))
		if( fgets( line, sizeof line, fpipe))
		{
			Writeline(m_socket, line, strlen(line));
			LOG("Print message to the client")
			//printf("%s", line);
		}
	LOG("Close pipe")
   pclose(fpipe);
   
   
   
   

	/*  Close socket  */

	if ( close(m_socket) < 0 ) {
	    LOG("Error calling close()")
	    return;
	}
	
	LOG("Socket has been closed")
	
	Stop();
}
		
void Connection::OnRun()
{
}

void Connection::OnAfterRun()
{
	if(GetMode() == rm_Process)
		close(m_socket);
}

void Connection::OnStop()
{
}

void Connection::OnAfterStop()
{
}